package guild

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gmlock"
	"time"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/httpserver"
	"xr-game-server/dao/guilddao"
	"xr-game-server/dao/roledao"
	"xr-game-server/dto/guilddto"
	"xr-game-server/entity"
	"xr-game-server/errercode"
)

// BlacklistApplicant 将申请人拉黑
func BlacklistApplicant(ctx context.Context, reqTemp *guilddto.GuildBlacklistReq) (bool, error) {
	// 获取当前用户角色
	roleId := httpserver.GetAuthId(ctx)
	// 获取操作者角色信息
	operatorRole := roledao.GetRoleByRole(roleId)

	// 检查操作者是否在公会中
	if operatorRole.GuildId == common.Zero {
		return false, errercode.CreateCode(errercode.GuildNonExist)
	}
	lockKey := fmt.Sprintf(GuildLock, operatorRole.GuildId)
	defer gmlock.Unlock(lockKey)
	lockFlag := gmlock.TryLock(lockKey)
	if !lockFlag {
		return false, errercode.CreateCode(errercode.SysBuyLimit)
	}
	// 检查操作者权限（只有会长和官员可以拉黑申请人）
	operatorMember := guilddao.GetMemberByRoleId(operatorRole.GuildId, roleId)
	if operatorMember.Title == entity.GuildMemberTitleMember {
		return false, errercode.CreateCode(errercode.NoPermission)
	}

	// 获取或创建申请记录
	applyData := guilddao.GetBlackListBy(operatorRole.GuildId, reqTemp.TargetRoleId)

	// 设置拉黑时间
	blackTime := time.Now().Add(time.Duration(reqTemp.BlacklistDays) * 24 * time.Hour)
	applyData.SetBlackTime(&blackTime)
	applyData.SetUpdatedAt(time.Now())
	applyData.SetIsDeleted(false)
	//删除申请列表
	guilddao.RemoveApply(operatorRole.GuildId, reqTemp.TargetRoleId)

	return true, nil
}
